package com.isoft.illustrationsdraw.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.isoft.illustrationsdraw.brief.BriefIllustrationInfo;
import com.isoft.illustrationsdraw.entity.Illustration;
import com.isoft.illustrationsdraw.entity.IllustrationTag;
import com.isoft.illustrationsdraw.entity.Tag;
import com.isoft.illustrationsdraw.mapper.IllustrationMapper;
import com.isoft.illustrationsdraw.service.IllustrationService;
import com.isoft.illustrationsdraw.service.IllustrationTagService;
import com.isoft.illustrationsdraw.service.TagService;


import java.util.List;


import org.springframework.stereotype.Service;

@Service
public class IllustrationServiceImpl extends ServiceImpl<IllustrationMapper, Illustration> implements IllustrationService {

    private final IllustrationMapper illustrationMapper;
    private final TagService tagService;
    private final IllustrationTagService illustrationTagService;

    public IllustrationServiceImpl(IllustrationTagService illustrationTagService, TagService tagService, IllustrationMapper illustrationMapper) {
        this.illustrationMapper = illustrationMapper;
        this.tagService = tagService;
        this.illustrationTagService = illustrationTagService;
    }

    @Override
    public List<Illustration> getRandomIllustration(Integer pageCount, Integer pageSize) {
        QueryWrapper<Illustration> queryWrapper = new QueryWrapper<>();
        // 添加 visibility 为 1 的条件
        queryWrapper.eq("visibility", 1); 
        // 按照随机排序
        queryWrapper.orderBy(true, true, "RAND()"); 
        
        Page<Illustration> page = new Page<>(pageCount, pageSize); // 分页，限制返回一条记录
        
        // 执行查询
        page(page, queryWrapper); // 这个方法已经会更新传入的 page 对象
        
        // 返回查询的结果（第一页，第一条记录）
        if (!page.getRecords().isEmpty()) {
            return page.getRecords();
        } else {
            return null; // 如果没有符合条件的记录
        }
    }
    
    @Override
    public List<Illustration> getIllustrationSortedByTimeWithPagination(Integer page) {
        // 创建 QueryWrapper，按 createdAt 字段升序排序
        QueryWrapper<Illustration> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByAsc("created_at"); // 这里是升序排序

        // 创建分页对象，指定当前页和每页记录数
        Page<Illustration> illustrationPage = new Page<>(page, 20);

        // 执行分页查询，并返回分页结果
        return illustrationMapper.selectPage(illustrationPage, queryWrapper).getRecords();
    }

}
